package com.wxgo.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wxgo.common.model.Module;

public class MenuUtils {

	public static Map<String, Object> getMenuList(Integer did, Integer rid) {
		// 查询权限菜单
		List<Module> ModuleList = Module.dao
				.find("select * from module where id in(select mid from power where rid=? ) order by od asc", rid);
		return dealMenuMap(ModuleList);
	}

	public static Map<String, Object> getAllMenuList() {
		// 查询权限菜单
		List<Module> ModuleList = Module.dao.find("select * from module order by od asc");
		return dealMenuMap(ModuleList);
	}

	private static Map<String, Object> dealMenuMap(List<Module> ModuleList) {
		// 存储权限菜单信息 mModule为主键的是主菜单，cModule为主键的为子菜单List
		Map<String, Object> ModuleMap = new HashMap<String, Object>();
		// 存储主菜单的list
		List<Module> mModuleList = new ArrayList<Module>();
		// 存储所有子菜单信息的Map
		Map<Integer, List<Module>> cModuleMap = new HashMap<Integer, List<Module>>();
		// 存储每个主菜单下子菜单的list
		List<Module> cModuleList = null;
		Integer parentid = null;
		for (Module Module : ModuleList) {
			// 如果是上级菜单，添加进主菜单List 并判断是否存在存储子菜单的Map
			parentid = Module.getPmid();
			if (parentid == 0) {
				mModuleList.add(Module);
			} else {
				if (cModuleMap.containsKey(parentid)) {
					cModuleMap.get(parentid).add(Module);
				} else {
					cModuleList = new ArrayList<Module>();
					cModuleList.add(Module);
					cModuleMap.put(parentid, cModuleList);
				}
			}
		}
		ModuleMap.put("mMenus", mModuleList);
		ModuleMap.put("cMenuMap", cModuleMap);
		return ModuleMap;
	}
}
